class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public boolean isBalanced(TreeNode root) {
        //空节点为平衡二叉树返回true
        if(root==null){
            return true;
        }
        //非空节点求两边子树的高度，判断是否相差超过1，超过则返回false
        int height1=getHeight(root.left);
        int height2=getHeight(root.right);
        if(height1-height2<-1||height1-height2>1){
            return false;
        }
        //递归判断左右子树是否也是平衡二叉树，出现非平衡二叉树则返回false
        if(!isBalanced(root.left)||!isBalanced(root.right)){
            return false;
        }
        //所有程序运行结束没有返回，说明整棵树为平衡二叉树
        return true;

    }
    //调用底层方法，获取二叉树的深度
    public int getHeight(TreeNode root){
        //空节点返回-1
        if(root==null){
            return -1 ;
        }
        //递归左子树
        int leftHeight=getHeight(root.left);
        //递归右子树
        int rightHeight=getHeight(root.right);
        //返回其中最大值
        return leftHeight>rightHeight?leftHeight+1:rightHeight+1;
    }
}